//
//  GameScene.swift
//  FlappyBird
//
//  Created by WTFKL on 17/9/4.
//  Copyright © 2017年 WTF. All rights reserved.
//

import SpriteKit
import GameplayKit

class GameScene: SKScene , SKPhysicsContactDelegate{
    
    //颜色
    var skyColor : SKColor!;
    
    var moving : SKNode!;
    
    // 管子
    var pipes : SKNode!;
    var pileTextUp : SKTexture!;
    var pileTextDown : SKTexture!;
    var movePliesAndRemove : SKAction!;
    
    //分数
    var score = NSInteger();
    
    var groundSp : SKSpriteNode? ;
    
    
    //小鸟
    var bird : SKSpriteNode!;
    //半轴
    var halfY :CGFloat!;
    var halfX :CGFloat!;
    
    
    
    
    //设置掩码
    let birdCategory : UInt32 = 1 << 0;//1
    let wordCategory : UInt32 = 1 << 1;//地面碰撞掩码,2
    let pipeCategory : UInt32 = 1 << 2;//管道碰撞掩码,4
    let scoreCategory : UInt32 = 1 << 3;//8
    
    //分数版节点
    var contactNode : SKNode!;
    
    //分数板
    var scoreLabel : SKLabelNode!;
    var gameOver : SKLabelNode!;
    var showScore : SKLabelNode!;
    var restartBtn : UIButton!;
    var scores = 0;
    
    
    
    override func didMove(to view: SKView) {
        //半轴
        halfY = self.frame.size.height/2;
        halfX = self.frame.size.width/2;
        
        gameOver = SKLabelNode(fontNamed: "Chalkduster");
        gameOver.text = "Game Over"
        gameOver.position = CGPoint(x: 0, y: 0);
        gameOver.setScale(2.0);
        gameOver.name = "gameOver";
        
        showScore = SKLabelNode(fontNamed: "Chalkduster");
        showScore.position = CGPoint(x: 0, y: -150);
        showScore.setScale(2.0);
        showScore.name = "showScore";
        
        restartBtn = UIButton();
        restartBtn.setImage(#imageLiteral(resourceName: "button_ok"), for: .normal);
        restartBtn.sizeToFit();
        restartBtn.center = CGPoint(x: view.center.x, y: view.center.y+150);
        restartBtn.addTarget(self, action: #selector(restart), for: .touchUpInside);
        restartBtn.isHidden = true;
        self.view?.addSubview(restartBtn);
        
        
        scoreLabel = SKLabelNode(fontNamed: "Chalkduster");
        scoreLabel.position = CGPoint(x: -halfX+150, y: -halfY+50);
        scoreLabel.zPosition = 20;
        scoreLabel.name = "scoreLabel";
        self.addChild(scoreLabel)
        
        setUpbackgroundTexture();
        setUpBird();
        self.physicsWorld.gravity = CGVector(dx: 0.0, dy: -5);
        bird.physicsBody = SKPhysicsBody(circleOfRadius: bird.size.height/2.0);
        bird.physicsBody?.isDynamic = true;
        bird.physicsBody?.allowsRotation = false;
        bird.name = "bird";
        pipes = SKNode();
        moving.name = "moving";
        moving.addChild(pipes);

        //移动距离
        pileTextUp = SKTexture(image: #imageLiteral(resourceName: "pipe_up"));
        pileTextUp.filteringMode = SKTextureFilteringMode.nearest;
        pileTextDown = SKTexture(image: #imageLiteral(resourceName: "pipe_down"));
        pileTextDown.filteringMode = SKTextureFilteringMode.nearest;
        
//        let distance = CGFloat(2*halfX+2*pileTextUp.size().width);
        let distance = 854.0;
        let movePipes = SKAction.moveBy(x:-2.0 * CGFloat( distance), y: 0.0, duration: TimeInterval(CGFloat(distance/100.0)));
        let removePipes = SKAction.removeFromParent();
        
        movePliesAndRemove = SKAction.sequence([movePipes,removePipes]);
       
        let spwan = SKAction.run {
            if(self.moving.speed > 0){
                self.spawnPipes()
            }
        }
        
        
        let  delay = SKAction.wait(forDuration: 2);
        print("-qweqwe+++",delay.duration);
//        print("time",2.0/Double(moving.speed));
        let spwanThenDelay = SKAction.sequence([spwan,delay]);
        
        let spwanThenDelayForever = SKAction.repeatForever(spwanThenDelay);
        
        self.run(spwanThenDelayForever);
        
        physicsWorld.contactDelegate = self;
        
        
    }
   
    
    //初始化小鸟
    func setUpBird(){
        let birdTexture1 = SKTexture(image: #imageLiteral(resourceName: "bird0_0"));
        let birdTexture2 = SKTexture(image: #imageLiteral(resourceName: "bird0_1"));
        let birdTexture3 = SKTexture(image: #imageLiteral(resourceName: "bird0_2"));
        
        birdTexture1.filteringMode = SKTextureFilteringMode.nearest;
        birdTexture2.filteringMode = SKTextureFilteringMode.nearest;
        birdTexture3.filteringMode = SKTextureFilteringMode.nearest;
        
        let animation = SKAction.animate(with: [birdTexture1,birdTexture2,birdTexture3], timePerFrame: 0.2);
        
        let flap = SKAction.repeatForever(animation);
        
        bird = SKSpriteNode(texture: birdTexture1);
        
        bird.setScale(2.0);
        
        bird.position = CGPoint(x:-200, y: -100);
        
        //categoryBitMask，它标记了物体属于那一类物体，默认值为0xffffffff
        //collisionBitMask，它标记了哪些物体可以跟其发生碰撞，默认值为0xffffffff
        //contactTestBitMask，它标记了哪些物体会和其发生碰撞后产生一些影响，默认值为0x00000000
        bird.physicsBody?.categoryBitMask = birdCategory;
        bird.physicsBody?.collisionBitMask = wordCategory | pipeCategory;
        bird.physicsBody?.contactTestBitMask = wordCategory | pipeCategory;
        
        bird.run(flap);
        self.addChild(bird);
    }
    
    //初始化天空地表纹理
    func  setUpbackgroundTexture() {
        skyColor = SKColor(red: 81.0/255, green: 192/255.0, blue: 201.0/255, alpha: 1.0);
        self.backgroundColor = skyColor;
        
        //移动节点
        moving = SKNode();
        self.addChild(moving);
        
        //创建纹理
        let groundTexture = SKTexture(imageNamed: "land");
        //过滤模式
        groundTexture.filteringMode = SKTextureFilteringMode.nearest;
        
        let groundWidth = groundTexture.size().width;
        
        //精灵动作
        let moveGroundSprite = SKAction.moveBy(x: -groundWidth*2.0, y: 0, duration: TimeInterval(0.01 * groundWidth * 2));
        
        //精灵还原动作
        let resetCroundSprite = SKAction.moveBy(x: groundWidth*2.0, y: 0, duration: 0.0);
    
        //永动,sequence-序列，组合精灵
        let moveGroundSpriteForever = SKAction.repeatForever(SKAction.sequence([moveGroundSprite,resetCroundSprite]));
        
        let groundtextureHeight = groundTexture.size().height;
        
        //初始化刚体地表（碰撞）
        let ground = SKNode();
        ground.position = CGPoint(x: 0, y: -(halfY-groundtextureHeight)+90);
        ground.physicsBody?.usesPreciseCollisionDetection = true;
        ground.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: self.frame.size.width, height: 1));
        ground.physicsBody?.isDynamic = false;
        ground.physicsBody?.categoryBitMask = wordCategory;
        ground.physicsBody?.contactTestBitMask = birdCategory;
        self.addChild(ground);
        
        //地表纹理
        for i in 0 ..< Int(2 + self.frame.size.width / (groundWidth * 2)) {
            let sprite = SKSpriteNode(texture: groundTexture);
            sprite.setScale(2.0);//设置规模
            sprite.position = CGPoint(x: CGFloat(i) * sprite.size.width-50, y: -(halfY-groundtextureHeight));
            print(groundTexture.size().height);
            sprite.run(moveGroundSpriteForever);//设置循环动作
            groundSp = sprite;
            moving.addChild(sprite);
        }
        
        
        //天空纹理
        let skyTexture = SKTexture(imageNamed: "bg_day");
        skyTexture.filteringMode = SKTextureFilteringMode.nearest;
        
        let skyWidth = skyTexture.size().width;
        let moveSkySprite = SKAction.moveBy(x: -skyWidth*2.0, y: 0, duration: TimeInterval(0.01 * skyWidth * 2));
        let resetSkySprite = SKAction.moveBy(x: skyWidth * 2.0 , y: 0, duration:0);
        let  moveSkyPriteForever = SKAction.repeatForever(SKAction.sequence([moveSkySprite,resetSkySprite]));
        
        
        
        for i in 0 ..< Int(2 + self.frame.size.width / (skyWidth * 2)) {
            let sprite = SKSpriteNode(texture: skyTexture);
            sprite.setScale(2.0);//设置规模
            sprite.zPosition = -20;
            sprite.position = CGPoint(x: CGFloat(i) * sprite.size.width-100, y: (groundSp?.position.y)!+skyTexture.size().height);
            sprite.run(moveSkyPriteForever);//设置循环动作
            moving.addChild(sprite);
        }
        
    }
    
    
    
    func touchDown(atPoint pos : CGPoint) {
        
    }
    
    func touchMoved(toPoint pos : CGPoint) {
      
    }
    
    func touchUp(atPoint pos : CGPoint) {
       
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if moving.speed > 0 {
            for touch : AnyObject in touches{
               _ = touch.location(in: self);
                bird.physicsBody?.velocity = CGVector(dx: 0, dy: 0);
                bird.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 100));//点击上升高度
            }
        }
    }
    
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    }
    
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    }
    
    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
    }
    
    //调整精灵位置状态等
    override func update(_ currentTime: TimeInterval) {
        // 旋转鸟头很复杂，表示看不懂
        bird.zRotation = self.clamp(min: -1, max: 0.5, value: (bird.physicsBody?.velocity.dy)! * (Int((bird.physicsBody?.velocity.dy)!) < 0 ? 0.003 : 0.001));
        if moving.speed > 0 {
            self.scores += 1;
            scoreLabel.text = "你飞行了：\(scores/10)米"
//            if scores/10 > 50{
//                moving.speed = 1.5;
//            } else if scores/10 > 500{
//                 moving.speed = 1.7;
//            } else if scores/10 > 700{
//                moving.speed = 1.9;
//            } else if scores/10 > 1000{
//                moving.speed = 2;
//            }
        }
       
    }
    
    func clamp(min:CGFloat , max : CGFloat ,value : CGFloat) -> CGFloat{
        if value > max {
            return max;
        }else if(value < min){
            return min;
        }else{
            return value;
        }
    }
    
    //生成管道
    func spawnPipes(){
        
        let pipePair = SKNode();
        pipePair.position = CGPoint(x:100 ,y:100);
        pipePair.zPosition = -10;//介于背景和地表之间
        
        //随机管道高度
        let pipeHeight = UInt32(pileTextUp.size().height/4);
        let pipeY = arc4random()%pipeHeight * 4 + pipeHeight;
      
        
        //创建下管道
        let pipeDown = SKSpriteNode(texture: pileTextDown);
        pipeDown.setScale(2.0);
        pipeDown.position = CGPoint(x: halfX, y: halfY - CGFloat(pipeY));
        
        pipeDown.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: pipeDown.size.width, height: pipeDown.size.height-20));
        
        pipeDown.physicsBody?.isDynamic = false;
        
        pipeDown.physicsBody?.categoryBitMask = pipeCategory;
        
        pipeDown.physicsBody?.contactTestBitMask = birdCategory;
        
        pipePair.addChild(pipeDown);
        
        //上管道
        let pipeUp = SKSpriteNode(texture: pileTextUp);
        
        pipeUp.setScale(2.0);
        
//        pipeUp.position = CGPoint(x: halfX, y: -(halfY-(groundSp?.position.y)!)+pipeUp.size.height + CGFloat(pipeY));
        pipeUp.position = CGPoint(x: halfX, y: pipeDown.position.y - pipeDown.size.height/2 - 200 - pipeUp.size.height/2);
        
        pipeUp.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: pipeUp.size.width, height: pipeUp.size.height-20));
        
        pipeUp.physicsBody?.isDynamic = false;
        
        pipeUp.physicsBody?.categoryBitMask = pipeCategory;
        
        pipeUp.physicsBody?.contactTestBitMask = birdCategory;
        
        pipePair.addChild(pipeUp);
        
//        //通过节点
//        contactNode = SKSpriteNode(texture: SKTexture(image: #imageLiteral(resourceName: "score_panel")));
//        contactNode.position = CGPoint(x: pipeDown.position.x, y: pipeUp.position.y + pipeUp.size.height/2 + 75);
//        contactNode.physicsBody = SKPhysicsBody(rectangleOf:CGSize(width: pipeDown.size.width, height: 126));
//        contactNode.physicsBody?.isDynamic = false;
//        print("----",self.frame.midY);
//        contactNode.physicsBody?.categoryBitMask = scoreCategory;
//        contactNode.physicsBody?.contactTestBitMask = birdCategory;
//        pipePair.addChild(contactNode);
        
        
        
        pipePair.run(movePliesAndRemove);
        //添加到管子总节点
        pipes.addChild(pipePair);
        
    }
    
    
    
    func didBegin(_ contact: SKPhysicsContact) {
       
        if moving.speed > 0 {
            if contact.bodyA.categoryBitMask == pipeCategory || contact.bodyA.categoryBitMask == wordCategory {
                moving.speed = 0;
                restartBtn.isHidden = false;
                self.addChild(gameOver);
                self.showScore.text = "你的最终成绩是:\(scores/10)米";
                self.addChild(showScore);
            }else{
                
            }
        }
   
    }
    
  
    
    func restart(){
        //小鸟归位
        bird.position =  CGPoint(x:-200, y: -100);
        bird.physicsBody?.velocity = CGVector(dx: 0, dy: 0);
        bird.speed = 0;
        bird.zRotation = 0;
    
        //移除管道的所有子节点
        pipes.removeAllChildren();
        //分数归零
        scores = 0;
        //速度归位
        moving.speed = 1;
        //按钮隐藏
        restartBtn.isHidden = true;
        // 移除gameover
        gameOver.removeFromParent();
        showScore.removeFromParent();
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
